package felix.things.router.mqtt.server.broker;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

/**
 * 通过SpringBoot启动服务
 *
 * @author Felix
 * @date 2019/8/21
 */
@Slf4j
@SpringBootApplication(scanBasePackages = {"felix.things.router.mqtt.server"})
public class MqttBrokerApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(MqttBrokerApplication.class);
        Environment env = application.run(args).getEnvironment();
        log(env);
    }

    /**
     * 格式化运行成功后输出项目地址
     *
     * @param env
     */
    private static void log(Environment env) {
        String port = env.getProperty("server.port");

        String mqttPort = env.getProperty("spring.mqtt.broker.mqttPort");
        String websocketEnabled = env.getProperty("spring.mqtt.broker.websocketEnabled");
        String websocketPort = env.getProperty("spring.mqtt.broker.websocket-port");
        String websocketPath = env.getProperty("spring.mqtt.broker.websocket-path");
        String credentialsType = env.getProperty("spring.mqtt.broker.credentials.type");
        credentialsType = StringUtils.isEmpty(credentialsType) ? "anonymous" : credentialsType;
        String address = null;
        try {
            address = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            address = "127.0.0.1";
            e.printStackTrace();
        }
        port = StringUtils.isEmpty(port) ? "8080" : port;
        mqttPort = StringUtils.isEmpty(mqttPort) ? "1883" : mqttPort;
        websocketPort = StringUtils.isEmpty(websocketPort) ? "9996" : websocketPort;
        websocketPath = StringUtils.isEmpty(websocketPath) ? "" : websocketPath;


        StringBuilder sb = new StringBuilder("\n----------------------------------------------------------\n");
        ArrayList<String> args = new ArrayList<>();
        sb.append("\tMqttBroker is running!\n");

        sb.append("\tManager: \thttp://{}:{}{}\n");
        args.add(address);
        args.add(port);
        args.add("/open/api/mqtt/info");

        sb.append("\tcredentialsType: \t{}\n");
        args.add(credentialsType);

        sb.append("\tMQTT: \t\t{}:{}\n");
        args.add(address);
        args.add(mqttPort);

        if (Boolean.parseBoolean(websocketEnabled)) {
            sb.append("\tWebsocket: \t{}:{}{}\n");
            args.add(address);
            args.add(websocketPort);
            args.add(websocketPath);
        }

        sb.append("----------------------------------------------------------");

        log.info(sb.toString(), args.toArray());
    }

}
